package com.leve.admin.controller;

import com.google.gson.Gson;
import com.leve.admin.domain.Content;
import com.leve.admin.domain.Ghost;
import com.leve.admin.domain.PictrueMsg;
import com.leve.admin.service.ReceiverService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;

@RestController
@RequestMapping("/receiver")
@Slf4j
public class ReceiverController {
    @Autowired
    private ReceiverService receiverService;
    private Gson gson = new Gson();

    @ApiOperation("云信消息转发")
    @PostMapping
    public Map<String, Object> receive(HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap();
        try {
            byte[] body = readBody(request);
            if (body == null) {
                log.info("request wrong, empty body!");
                result.put("code", Integer.valueOf(414));
                return result;
            }
            String ContentType = request.getContentType();
            String AppKey = request.getHeader("AppKey");
            String CurTime = request.getHeader("CurTime");
            String MD5 = request.getHeader("MD5");
            String CheckSum = request.getHeader("CheckSum");
            log.info("request headers: ContentType = {}, AppKey = {}, CurTime = {}, MD5 = {}, CheckSum = {}",
                    new Object[]{ContentType, AppKey, CurTime, MD5, CheckSum});
            String requestBody = new String(body, "UTF-8");
            Map copyMsgDto = (Map) gson.fromJson(requestBody, Map.class);
            Object eventType = copyMsgDto.get("eventType");
            Object convType = copyMsgDto.get("convType");
            Object tMemberList = copyMsgDto.get("tMembers");
            String fromAccount = copyMsgDto.get("fromAccount").toString();
            String msgType = copyMsgDto.get("msgType").toString();
            Object msgObj = copyMsgDto.get("body");
            String to = copyMsgDto.get("to").toString();
            Object attach = copyMsgDto.get("attach");

            log.info("Map{}", copyMsgDto.get("attach"));

            log.info("EventType:{}", eventType);
            log.info("ConvType:{}", convType);
            log.info("request body = {}", requestBody);
            log.info("MsgType:{}", msgType);
            log.info("Msg:{}", msgObj);
            if ("1".equals(eventType)) {
                if ("TEAM".equals(convType)) {
                    log.info("===============Already into the little ghost conversation====================");
                    String[] tMembers = tMemberList.toString().replace("[", "").replace("]", "").split(",");
                    log.info("tMembers:{} {}", tMembers[0], Integer.valueOf(tMembers.length));
                    if (tMembers.length == 1) {
                        Document customer = receiverService.isCustomer(tMembers[0]);
                        if (customer != null) {
                            Boolean virtual = (Boolean) customer.get("virtual");
                            if (virtual && (!"leve_oper_team".equals(fromAccount.trim()))) {
                                String msg = msgObj.toString();
                                String[] msgList = msg.split("##");
                                if (msgList.length < 2) {
                                    String[] msgList2 = msg.split("::");
                                    if ((msgList2.length >= 2) && (msgList2.length <= 2)) {
                                        String otherAccId = msgList2[1];

                                        this.receiverService.sendMessage(to.toString(), otherAccId, msgList2[0]);
                                    } else if (!"leve_oper_team".equals(fromAccount.trim())) {
                                        //目前还没有想到很好的办法来解决合理分发的问题
                                        //现在是根据nickname长度进行分发,已知bug. nickname长度发生变化后,聊天对象会发生改变
                                        String nickname = customer.getString("nickname");
                                        int length = nickname.length();
                                        String toAccid = "leve_117779";
                                        if ((length >= 1) && (length <= 2)) {
                                            toAccid = "leve_117779";
                                        }
                                        if ((length >= 3) && (length <= 5)) {
                                            toAccid = "leve_117780";
                                        }
                                        if ((length >= 6) && (length <= 7)) {
                                            toAccid = "leve_117781";
                                        }
                                        if (length >= 8) {
                                            toAccid = "leve_117782";
                                        }
                                        if ("PICTURE".equals(msgType)) {
                                            PictrueMsg pictrueMsg = (PictrueMsg) gson.fromJson(attach.toString(), PictrueMsg.class);

                                            this.receiverService.sendMessage(customer.getString("im_id"), toAccid, pictrueMsg, "1",
                                                    fromAccount);
                                        } else if ("CUSTOM".equals(msgType)) {
                                            Content content = (Content) gson.fromJson(attach.toString(), Content.class);
                                            this.receiverService.sendMessage(customer.getString("im_id"), toAccid, attach, "0", fromAccount);
                                        } else {
                                            this.receiverService.sendMessage(customer.getString("im_id"), toAccid,
                                                    msg + "##" + fromAccount);
                                        }
                                    }
                                }
                            }
                        }

                    }
                } else if ("PERSON".equals(convType)) {
                    //TODO 客服号
                    Document customer = receiverService.isCustomer(to);
                    if (customer != null) {
                        Boolean virtual = (Boolean) customer.get("virtual");
                        if (virtual && (!"leve_oper_team".equals(to.trim()))) {
                            String msg = msgObj.toString();
                            String[] msgList = msg.split("##");
                            if (msgList.length < 2) {
                                String[] msgList2 = msg.split("::");
                                if ((msgList2.length >= 2) && (msgList2.length <= 2)) {
                                    String otherAccId = msgList2[1];
                                    this.receiverService.sendMessage(to, otherAccId, msgList2[0]);
                                } else if (!"leve_oper_team".equals(fromAccount.trim())) {
                                    //目前还没有想到很好的办法来解决合理分发的问题
                                    //现在是根据nickname长度进行分发,已知bug. nickname长度发生变化后,聊天对象会发生改变
                                    String nickname = customer.getString("nickname");
                                    int length = nickname.length();
                                    String toAccid = "leve_117779";
                                    if ((length >= 1) && (length <= 2)) {
                                        toAccid = "leve_117779";
                                    }
                                    if ((length >= 3) && (length <= 5)) {
                                        toAccid = "leve_117780";
                                    }
                                    if ((length >= 6) && (length <= 7)) {
                                        toAccid = "leve_117781";
                                    }
                                    if (length >= 8) {
                                        toAccid = "leve_117782";
                                    }
                                    Gson gson = new Gson();
                                    if ("PICTURE".equals(msgType)) {
                                        PictrueMsg pictrueMsg = (PictrueMsg) gson.fromJson(attach.toString(), PictrueMsg.class);

                                        this.receiverService.sendMessage(customer.getString("im_id"), toAccid, pictrueMsg, "1",
                                                fromAccount);
                                    } else if ("CUSTOM".equals(msgType)) {
                                        Content content = (Content) gson.fromJson(attach.toString(), Content.class);
                                        this.receiverService.sendMessage(customer.getString("im_id"), toAccid, attach, "0",
                                                fromAccount);
                                    } else {
                                        this.receiverService.sendMessage(customer.getString("im_id"), toAccid,
                                                msg + "##" + fromAccount);
                                    }
                                }
                            }
                        }
                    }

                }
            }
            result.put("code", Integer.valueOf(200));
            return result;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            result.put("code", Integer.valueOf(414));
        }
        return result;
    }

    private byte[] readBody(HttpServletRequest request)
            throws IOException {
        if (request.getContentLength() > 0) {
            byte[] body = new byte[request.getContentLength()];
            IOUtils.readFully(request.getInputStream(), body);
            return body;
        }
        return null;
    }

    @GetMapping("/sendMsg.do")
    public String sendMsg() {
        Future<String> sendMessage = this.receiverService.sendMessage("leve_119846", "carmen", "����IM����");
        return sendMessage.toString();
    }

    @ApiOperation("客服号进行打招呼")
    @PostMapping(value = "toSay", consumes = APPLICATION_JSON_UTF8_VALUE)
    public String toSay(@Valid @RequestBody Ghost ghost)
            throws Exception {
        return this.receiverService.toSay(ghost);
    }

    @ResponseBody
    @GetMapping("/findGhost")
    public String findGhost()
            throws Exception {
        return this.receiverService.findGhost();
    }

    @ResponseBody
    @GetMapping("/testToSay.do")
    public String testToSay()
            throws Exception {
        return this.receiverService.testToSay();
    }


    @ResponseBody
    @GetMapping(value = {"{accid}/joinTeams.do"})
    public String joinTeams(@PathVariable("accid") String accid)
            throws Exception {
        return this.receiverService.joinTeams(accid);
    }

    @ResponseBody
    @GetMapping(value = {"{from}/{to}/sendUp.do"})
    public String sendUp(@PathVariable("from") String from, @PathVariable("to") String to)
            throws Exception {
        return this.receiverService.sendUp(from, to);
    }

    @ResponseBody
    @GetMapping(value = {"{userAccid}/{adminAccid}/findGhost.do"})
    public Map<String, Object> findGhost(@PathVariable("userAccid") String userAccid, @PathVariable("adminAccid") String adminAccid)
            throws Exception {
        return this.receiverService.findGhost(userAccid, adminAccid);
    }
}
